﻿using System.Configuration;
using System.Web.Configuration;

namespace Songhay.Web.Mvc.ViewModels
{
    /// <summary>
    /// Defines <c>Web.config</c> state information.
    /// </summary>
    public class WebConfigViewModel
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="WebConfigViewModel"/> class.
        /// </summary>
        public WebConfigViewModel()
        {
            this._configuration = WebConfigurationManager.OpenWebConfiguration("~");
            this._connectionStringsSection = this._configuration.GetSection("connectionStrings");
            if(this._connectionStringsSection == null) throw new ConfigurationErrorsException("Section “connectionStrings” not found");
        }

        /// <summary>
        /// Gets a value indicating whether the connection strings section is protected.
        /// </summary>
        /// <value>
        ///     <c>true</c> if connection strings section is protected; otherwise, <c>false</c>.
        /// </value>
        public bool ConnectionStringsIsProtected { get { return this._connectionStringsSection.SectionInformation.IsProtected; } }

        /// <summary>
        /// Protects/unprotect the connection strings section.
        /// </summary>
        public void ProtectUnprotectConnectionStringsSection()
        {
            if(this.ConnectionStringsIsProtected)
            {
                this._connectionStringsSection.SectionInformation.UnprotectSection();
            }
            else
            {
                this._connectionStringsSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
            }
            this._configuration.Save();
        }

        Configuration _configuration;
        ConfigurationSection _connectionStringsSection;
    }
}
